const { buildMain } =  require('./build-main')
const { buildRender } = require('./build')
const { spawn } = require('child_process')
const colors = require('colors-console')
const path = require('path')
const packageJson = require('../main_package.json')
const fs = require('fs')


function buildPackJson() {
  // const pickKeys = ['name', 'version', 'main']
  //
  // const obj = Object.keys(packageJson).reduce((obj, key) => {
  //   if (pickKeys.includes(key)) {
  //     obj[key] = packageJson[key]
  //   }
  //
  //   return obj
  // }, {})
  //
  const jsonPage = path.join(__dirname, '../dist/package.json')
  //
  fs.writeFileSync(jsonPage, JSON.stringify(packageJson), 'utf-8')
  //
  console.log(colors('green', 'package.json生成成功'))
}


function runElectronBuild() {
  const handle = spawn(path.join(__dirname, '../node_modules/.bin/electron-builder.cmd'))

  return new Promise((resolve, reject) => {
    handle.stdout.on('data', data => {
      console.log(`electron builder: ${data}`)
    })

    // stderr 获取标准错误输出
    handle.stderr.on('data', data => {
      console.error(`electron builder err output: ${data}`)
    })

    handle.on('close', code => {
      console.log(`electron builder exit: ${code}`)
      code === 1 ? reject() : resolve()
    })

    handle.on('error', code => {
      console.log(`electron builder err ${code}`)
      reject()
      // downLiveServer()
    })
  })
}

async function build() {
  try {
    console.log(colors('yellow','开始打包渲染进程代码'))
    await buildRender()

    console.log(colors('yellow','开始编译主进程代码'))
    await buildMain('prod')

    console.log(colors('yellow', '开始生成package.json'))
    buildPackJson()

    console.log(colors('yellow', '开始运行electron builder'))
    await runElectronBuild()
    console.log(colors('green', '构建完毕'))
  } catch (err) {
    console.log(colors('red', '构建失败', err))
  }

}

build()